$(document).ready(function() {
	
	startLoadingTitle();
	
	$.ajax({
		type: "GET",
		url: '/rest/switch',
		success: function(data){
			refreshStatus(data);
		},
		error: function (data) {
			console.log(data);
		}
	});
	
	$.ajax({
		type: "GET",
		url: '/rest/loginlink',
		success: function(data){
			
			if (data['loggedIn']) {
				$('#logOutLink').html(data['link']);
				setTimeout(function() {
					$('#loading').hide('slow');
					$('#content').show('slow');
					stopLoadingTitle();
				},1500);
			} else {
				$('#loading').hide('slow');
				$('#logIn').show('slow');
				$('#logInLink').html(data['link']);
			}
			
		},
		error: function (data) {
			console.log(data);
		}
	});
	
	$('input.switch-input').change(function() {
		switchRequest(this.id, this.checked);
	});
	
	$('#summer').mousedown(function() {
		switchRequest("summer", true);
	});
	
	$('#summer').mouseup(function() {
		switchRequest("summer", false);
	});
	
	
	if (window.addEventListener) {
		var keys = [];
		var konami = "38,38,40,40,37,39,37,39,66,65,13";
		window.addEventListener("keydown", function(e){
			keys.push(e.keyCode);
			if (keys.toString().indexOf(konami) >= 0) {
				alert('Konami!');
				keys = [];
			};
		}, true);
	}
	
	
});

var loadingInterval;

var loadingDots = 1;

function refreshStatus(data) {
	$.each( $('input.switch-input'), function( i, l ) {
			$('#' + l.id).prop('checked', data[l.id]);
	});
}

function switchRequest(id, state) {

	$.ajax({
		type: "POST",
		url: '/rest/switch',
		data: {
			'id': id,
			'action': state
		},
		success: function(data){
			refreshStatus(data);
		},
		error: function (data) {
			console.log(data);
		}
	});
}

function startLoadingTitle() {
	loadingInterval = setInterval(function(){loadingTitleTimer()},500);
}

function stopLoadingTitle() {
	clearInterval(loadingInterval);
	document.title = "Drsch";
}

function loadingTitleTimer() {
	if (loadingDots == 0) {
		document.title = "Loading";
		loadingDots = 1;
	} else if (loadingDots == 1) {
		document.title = "Loading.";
		loadingDots = 2;
	} else if (loadingDots == 2) {
		document.title = "Loading..";
		loadingDots = 3;
	} else {
		document.title = "Loading...";
		loadingDots = 0;
	}
}
